package io.xxx.omni.oss.custom

import io.xxx.omni.oss.common.format
import io.xxx.omni.oss.core.PageSynchronizer
import org.springframework.core.ParameterizedTypeReference
import org.springframework.http.HttpMethod
import org.springframework.http.RequestEntity
import org.springframework.web.util.UriComponentsBuilder

/**
 * 淘宝
 */
// https://open.taobao.com/
abstract class TbSynchronizer : PageSynchronizer<Map<String, Any>>() {

    protected abstract val path: String

    override val pageSize = 500

    override fun getResponse(context: Context, pageNo: Int, containsTotal: Boolean): Map<String, Any> {
        val (startTime, endTime) = context
        val url = UriComponentsBuilder
            .fromHttpUrl(proxyProperties.httpUrls["taobao"]!!)
            .path(path)
            .queryParam("sellerNick", store.oname)
            .queryParam("startTime", startTime.format())
            .queryParam("endTime", endTime.format())
            .queryParam("pageSize", pageSize.toString())
            .queryParam("pageNo", pageNo)
            .queryParam("counted", containsTotal)
            .build()
            .toUri()

        val responseType = object : ParameterizedTypeReference<Map<String, Any>>() {}
        val request = RequestEntity(null, HttpMethod.GET, url)
        return restTemplate.exchange(request, responseType).body!!
    }

    override fun getCount(context: Context, response: Map<String, Any>): Int {
        return response["count"] as Int
    }
}